//
//  YKPlaceholderTextView.m
//  baisi
//
//  Created by 吴高烽 on 2016/10/30.
//  Copyright © 2016年 吴高烽. All rights reserved.
//  做第三方框架是要考虑一下独立性，不要依赖别的的框架
/**
 * setNeedsDisplay方法 : 会在恰当的时刻自动调用drawRect:方法
 * setNeedsLayout方法 : 会在恰当的时刻调用layoutSubviews方法
 */
#import "YKPlaceholderTextView.h"
#import "UIView+YKFrame.h"
@interface YKPlaceholderTextView ()
/** 占位文字label */
@property (nonatomic ,weak)UILabel *placeholderLabel;
@end
@implementation YKPlaceholderTextView
-(UILabel *)placeholderLabel{
    if (!_placeholderLabel) {
        UILabel *placeholderLabel = [[UILabel alloc]init];
        placeholderLabel.numberOfLines = 0 ;
        placeholderLabel.x = 8 ;
        placeholderLabel.y = 7 ;
        [self addSubview:placeholderLabel];
        _placeholderLabel = placeholderLabel ;
    }
    return _placeholderLabel ;
}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self =[super initWithFrame:frame]) {
//        垂直方向上永远有弹簧效果
        self.alwaysBounceVertical = YES ;
        self.font = [UIFont systemFontOfSize:15];
        self.placholderColor = [UIColor grayColor];
        
        [self setUpAllChilen];
    }
    return self;
}
-(void)setUpAllChilen{
    [YKNotiCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];
    
}
-(void)textDidChange{
    self.placeholderLabel.hidden = self.hasText ;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    self.placeholderLabel.width = self.width - 2*self.placeholderLabel.x ;
    [self.placeholderLabel sizeToFit];
//    当textView的宽度不是屏幕的宽度时，计算的size就会有问题，所以采用上面的方法比较好
//    CGSize maxSize = CGSizeMake(SCWidth - 2 * self.placeholderLabel.x, MAXFLOAT);
//    self.placeholderLabel.size = [self.placeholder boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.font } context:nil].size  ;
}
-(void)setFont:(UIFont *)font{
    [super setFont:font];
    self.placeholderLabel.font = font ;
    [self setNeedsLayout];
}
-(void)setPlaceholder:(NSString *)placeholder{
    _placeholder = [placeholder copy];
    self.placeholderLabel.text = placeholder ;
    [self setNeedsLayout];
}
-(void)setPlacholderColor:(UIColor *)placholderColor{
    _placholderColor = placholderColor ;
    self.placeholderLabel.textColor = placholderColor ;
    
}
-(void)setText:(NSString *)text{
    [super setText:text];
    [self textDidChange];
}
-(void)setAttributedText:(NSAttributedString *)attributedText{
    [super setAttributedText:attributedText];
    [self textDidChange];
}
-(void)dealloc{
    [YKNotiCenter removeObserver:self];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
